package activity.projeto;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.Random;

import org.andengine.engine.camera.BoundCamera;
import org.andengine.engine.camera.Camera;
import org.andengine.engine.camera.hud.HUD;
import org.andengine.engine.camera.hud.controls.AnalogOnScreenControl;
import org.andengine.engine.camera.hud.controls.AnalogOnScreenControl.IAnalogOnScreenControlListener;
import org.andengine.engine.camera.hud.controls.BaseOnScreenControl;
import org.andengine.engine.handler.IUpdateHandler;
import org.andengine.engine.handler.physics.PhysicsHandler;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.andengine.entity.IEntity;
import org.andengine.entity.modifier.LoopEntityModifier;
import org.andengine.entity.modifier.MoveModifier;
import org.andengine.entity.modifier.PathModifier;
import org.andengine.entity.modifier.PathModifier.IPathModifierListener;
import org.andengine.entity.modifier.PathModifier.Path;
import org.andengine.entity.modifier.RotationModifier;
import org.andengine.entity.primitive.Rectangle;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.scene.background.Background;
import org.andengine.entity.scene.menu.MenuScene;
import org.andengine.entity.scene.menu.MenuScene.IOnMenuItemClickListener;
import org.andengine.entity.scene.menu.item.IMenuItem;
import org.andengine.entity.scene.menu.item.SpriteMenuItem;
import org.andengine.entity.sprite.Sprite;
import org.andengine.entity.text.Text;
import org.andengine.entity.util.FPSLogger;

import org.andengine.extension.physics.box2d.FixedStepPhysicsWorld;
import org.andengine.extension.physics.box2d.PhysicsConnector;
import org.andengine.extension.physics.box2d.PhysicsFactory;
import org.andengine.extension.physics.box2d.PhysicsWorld;
import org.andengine.extension.physics.box2d.util.Vector2Pool;
import org.andengine.extension.tmx.TMXLayer;
import org.andengine.extension.tmx.TMXLoader;
import org.andengine.extension.tmx.TMXProperties;
import org.andengine.extension.tmx.TMXTile;
import org.andengine.extension.tmx.TMXTileProperty;
import org.andengine.extension.tmx.TMXTiledMap;
import org.andengine.extension.tmx.TMXLoader.ITMXTilePropertiesListener;
import org.andengine.extension.tmx.util.exception.TMXLoadException;
import org.andengine.input.touch.TouchEvent;
import org.andengine.input.touch.controller.MultiTouch;
import org.andengine.opengl.font.Font;
import org.andengine.opengl.texture.ITexture;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.vbo.VertexBufferObjectManager;
import org.andengine.ui.activity.SimpleBaseGameActivity;
import org.andengine.util.color.Color;
import org.andengine.util.debug.Debug;
import org.andengine.util.math.MathUtils;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;

import dados.Cooldown;

import activity.projeto.Planeta1;

import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.opengl.GLES20;
import android.view.KeyEvent;
import android.widget.Toast;

public class Planeta1 extends SimpleBaseGameActivity implements IOnMenuItemClickListener {
	MediaPlayer tiro = new MediaPlayer(); //objeto do audio
	Context  context = Planeta1.this; /*especifique o context ou obtenha usando um getBaseContext(); */
	//MediaPlayer back = new MediaPlayer(); //objeto do audio
	MediaPlayer etiro = new MediaPlayer(); //objeto do audio
	// ===========================================================
	// Constants
	// ===========================================================

	private static final int CAMERA_WIDTH = 480;
	private static final int CAMERA_HEIGHT = 320;
	
	protected static final int MENU_RESET = 0;
	protected static final int MENU_QUIT = MENU_RESET + 1;

	// ===========================================================
	// Fields
	// ===========================================================
	//---------------------------------- Camera --------------------------------------------
	protected BoundCamera mBoundChaseCamera;
	//---------------------------------	 Fisica do jogo	------------------------------------
	private PhysicsWorld mPhysicsWorld;
	//---------------------------------- Mapa ----------------------------------------------
	private TMXTiledMap mTMXTiledMap;
	//---------------------------------- Botoes --------------------------------------------
	private BitmapTextureAtlas botaoAtirarTexture;
	private ITextureRegion botaoAtirarTextureRegion;

	private BitmapTextureAtlas botaoTiro1Texture;
	private ITextureRegion botaoTiro1TextureRegion;

	private BitmapTextureAtlas botaoEspecialTexture;
	private ITextureRegion botaoEspecialTextureRegion;

	private BitmapTextureAtlas botaoDefesaTexture;
	private ITextureRegion botaoDefesaTextureRegion;

	private BitmapTextureAtlas botaoConsumableTexture;
	private ITextureRegion botaoConsumableTextureRegion;
	//---------------------------------- Controles -----------------------------------------
	private BitmapTextureAtlas mBitmapTextureAtlas;
	private ITextureRegion mNaveTextureRegion;
	private BitmapTextureAtlas mOnScreenControlTexture;
	private ITextureRegion mOnScreenControlBaseTextureRegion;
	private ITextureRegion mOnScreenControlKnobTextureRegion;
	private boolean mPlaceOnScreenControlsAtDifferentVerticalLocations = false;
	//---------------------------------- Menu ----------------------------------------------
	private BitmapTextureAtlas mMenuTexture;
	protected MenuScene mMenuScene;
	protected ITextureRegion mMenuResetTextureRegion;
	protected ITextureRegion mMenuQuitTextureRegion;
	//---------------------------------- Fontes --------------------------------------------
	private BitmapTextureAtlas mFontTexture;
	private Font mFont;
	//---------------------------------- Tiro ----------------------------------------------
	private BitmapTextureAtlas mBalasTexture;
	private ITextureRegion mBalaTextureRegion;
	
	private BitmapTextureAtlas mBalasEspeciasTexture;
	private ITextureRegion mBalaEspeciasTextureRegion;
	
	private BitmapTextureAtlas mBalasEnemyTexture;
	private ITextureRegion mBalaEnemyTextureRegion;
	
	private Bullet b;
	private BulletEnemy enemyTiro;
	//---------------------------------- Barras --------------------------------------------
	private Rectangle life;
	private Rectangle energy;
	private Rectangle cast;
	private Rectangle castBackground;
	//---------------------------------- Score ---------------------------------------------
	private int score = 0;
	private Text textRight;
	//---------------------------------- Naves ---------------------------------------------
	private int vida = 160;
	private Rectangle enemy1;
	private Rectangle enemy3;
	private int lifeEnemy1 = 160;
	private Rectangle enemy2;
	private int lifeEnemy2 = 160;
	private Sprite nave;
	private Body navebody;
	private Body enemy3Corpo;
	//---------------------------------- Outros --------------------------------------------
	private int contador = 0;
	private int PODER_TIRO = 25;
	protected int mCactusCount;
	private int velocidade = 5;
	private final int maxValueOfProgressBar = 160;
	private int contCast = 150;
	private int valorAtual;
	private int energia = 160;
	public static Planeta1 instance;
	public LinkedList<Bullet> bulletList = new LinkedList();
	public LinkedList<BulletEnemy> bulletListEnemy = new LinkedList();
	public int bulletCount = 0;
	private Body quadri;
	protected Scene scene;
	private TMXLayer tmxLayer;
	private Vector2 velocity;
	private HUD hud = new HUD();
	private AnalogOnScreenControl velocityOnScreenControl;
	private int menuClickCont=0;

	

	// ===========================================================
	// Constructors
	// ===========================================================

	// ===========================================================
	// Getter & Setter
	// ===========================================================
	
	public static Planeta1 getSharedInstance() {
		return instance;
	}
	
	// ===========================================================
	// Methods for/from SuperClass/Interfaces
	// ===========================================================
	
	@Override
	public EngineOptions onCreateEngineOptions() {
		instance = this;

		this.mBoundChaseCamera = new BoundCamera(0, 0, CAMERA_WIDTH,
				CAMERA_HEIGHT);

		if (MultiTouch.isSupported(this)) {
			if (MultiTouch.isSupportedDistinct(this)) {

			} else {
				this.mPlaceOnScreenControlsAtDifferentVerticalLocations = true;
				Toast.makeText(
						this,
						"MultiTouch detected, but your device has problems distinguishing between fingers.\n\nControls are placed at different vertical locations.",
						Toast.LENGTH_LONG).show();
			}
		} else {
			Toast.makeText(
					this,
					"Sorry your device does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.",
					Toast.LENGTH_LONG).show();
		}

		final EngineOptions engineOptions = new EngineOptions(true,
				ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(
						CAMERA_WIDTH, CAMERA_HEIGHT), this.mBoundChaseCamera);
		engineOptions.getTouchOptions().setNeedsMultiTouch(true);
		
		//-----------Audio------------------
				//back.release(); //prepara activity
		       //  back = MediaPlayer.create(context , R.raw.trilhajogo); //cria
		    
				//----------------------------------------
				

		return engineOptions;
	}

	@Override
	public void onCreateResources() {
		BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");

		this.mBitmapTextureAtlas = new BitmapTextureAtlas(
				this.getTextureManager(), 64, 64, TextureOptions.DEFAULT);
		this.mNaveTextureRegion = BitmapTextureAtlasTextureRegionFactory
				.createFromAsset(this.mBitmapTextureAtlas, this,
						"nave1.png", 0, 0);
		this.mBitmapTextureAtlas.load();

		this.mOnScreenControlTexture = new BitmapTextureAtlas(
				this.getTextureManager(), 256, 128, TextureOptions.BILINEAR);
		this.mOnScreenControlBaseTextureRegion = BitmapTextureAtlasTextureRegionFactory
				.createFromAsset(this.mOnScreenControlTexture, this,
						"base_base.png", 0, 0);
		this.mOnScreenControlKnobTextureRegion = BitmapTextureAtlasTextureRegionFactory
				.createFromAsset(this.mOnScreenControlTexture, this,
						"botao_movimentacao.png", 128, 0);
		this.mOnScreenControlTexture.load();

		this.botaoAtirarTexture = new BitmapTextureAtlas(
				this.getTextureManager(), 64, 64, TextureOptions.BILINEAR);
		this.botaoAtirarTextureRegion = BitmapTextureAtlasTextureRegionFactory
				.createFromAsset(this.botaoAtirarTexture, this,
						"botao_atirar.png", 0, 0);
		this.botaoAtirarTexture.load();

		this.botaoTiro1Texture = new BitmapTextureAtlas(
				this.getTextureManager(), 64, 64, TextureOptions.BILINEAR);
		this.botaoTiro1TextureRegion = BitmapTextureAtlasTextureRegionFactory
				.createFromAsset(this.botaoTiro1Texture, this, "next42-42.png",
						0, 0);
		this.botaoTiro1Texture.load();

		this.botaoConsumableTexture = new BitmapTextureAtlas(
				this.getTextureManager(), 64, 64, TextureOptions.BILINEAR);
		this.botaoConsumableTextureRegion = BitmapTextureAtlasTextureRegionFactory
				.createFromAsset(this.botaoConsumableTexture, this,
						"consumable.png", 0, 0);
		this.botaoConsumableTexture.load();

		this.botaoEspecialTexture = new BitmapTextureAtlas(
				this.getTextureManager(), 64, 64, TextureOptions.BILINEAR);
		this.botaoEspecialTextureRegion = BitmapTextureAtlasTextureRegionFactory
				.createFromAsset(this.botaoEspecialTexture, this,
						"especial.png", 0, 0);
		this.botaoEspecialTexture.load();
		this.mBitmapTextureAtlas.load();

		this.botaoDefesaTexture = new BitmapTextureAtlas(
				this.getTextureManager(), 64, 64, TextureOptions.BILINEAR);
		this.botaoDefesaTextureRegion = BitmapTextureAtlasTextureRegionFactory
				.createFromAsset(this.botaoDefesaTexture, this,
						"botao_defesa.png", 0, 0);
		this.botaoDefesaTexture.load();
		
		
 //----------------------Imagem do tiro --------------------------------------
		//------ tiro normal--------
		this.mBalasTexture = new BitmapTextureAtlas(this.getTextureManager(),
				16, 16, TextureOptions.BILINEAR);
		this.mBalaTextureRegion = BitmapTextureAtlasTextureRegionFactory
				.createFromAsset(this.mBalasTexture, this, "fireball-shot16-16.png", 0,
						0);
		this.mBalasTexture.load();
		
		//--------tiro especial--------
		this.mBalasEspeciasTexture = new BitmapTextureAtlas(this.getTextureManager(),
				32, 32, TextureOptions.BILINEAR);
		this.mBalaEspeciasTextureRegion = BitmapTextureAtlasTextureRegionFactory
				.createFromAsset(this.mBalasEspeciasTexture , this, "fireball-shot32-32.png", 0,
						0);
		this.mBalasEspeciasTexture.load();
		
		
//---------------------------------------------------------------------------
		
		
		
		this.mFontTexture = new BitmapTextureAtlas(this.getTextureManager(),
				256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mFont = new Font(this.getFontManager(), this.mFontTexture,
				Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 20, true,
				Color.BLUE);
		this.mEngine.getTextureManager().loadTexture(this.mFontTexture);
		this.getFontManager().loadFont(this.mFont);
		
		this.mMenuTexture = new BitmapTextureAtlas(this.getTextureManager(), 256, 128, TextureOptions.BILINEAR);
		this.mMenuResetTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mMenuTexture, this, "menu_reset.png", 0, 0);
		this.mMenuQuitTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mMenuTexture, this, "menu_quit.png", 0, 50);
		this.mMenuTexture.load();
	}

	@Override
	public Scene onCreateScene() {
		this.mEngine.registerUpdateHandler(new FPSLogger());
		
		this.createMenuScene();

		this.scene = new Scene();
		

		try {
			final TMXLoader tmxLoader = new TMXLoader(this.getAssets(),
					this.mEngine.getTextureManager(),
					TextureOptions.BILINEAR_PREMULTIPLYALPHA,
					this.getVertexBufferObjectManager(),
					new ITMXTilePropertiesListener() {
						@Override
						public void onTMXTileWithPropertiesCreated(
								final TMXTiledMap pTMXTiledMap,
								final TMXLayer pTMXLayer,
								final TMXTile pTMXTile,
								final TMXProperties<TMXTileProperty> pTMXTileProperties) {
							/*
							 * We are going to count the tiles that have the
							 * property "cactus=true" set.
							 */
							if (pTMXTileProperties.containsTMXProperty(
									"cactus", "true")) {
								Planeta1.this.mCactusCount++;
							}
						}
					});
			this.mTMXTiledMap = tmxLoader.loadFromAsset("tmx/space.tmx");

			this.runOnUiThread(new Runnable() {
				@Override
				public void run() {

				}
			});
		} catch (final TMXLoadException e) {
			Debug.e(e);
		}

		this.tmxLayer = this.mTMXTiledMap.getTMXLayers().get(0);
		scene.attachChild(tmxLayer);

		/* Make the camera not exceed the bounds of the TMXEntity. */
		this.mBoundChaseCamera.setBounds(0, 0, tmxLayer.getHeight(),
				tmxLayer.getWidth());
		this.mBoundChaseCamera.setBoundsEnabled(true);

		Planeta1.this.b = new Bullet(0);
		Planeta1.this.enemyTiro = new BulletEnemy();
		Planeta1.this.enemy1 = new Rectangle(30, 30, 0, 0,
				this.getVertexBufferObjectManager());
		Planeta1.this.enemy2 = new Rectangle(500, 500, 0, 0,
				this.getVertexBufferObjectManager());
		
		


		/* criar o "mundo" */
		this.mPhysicsWorld = new FixedStepPhysicsWorld(30, new Vector2(0, 0),
				false, 8, 1);

		/*
		 * Calculate the coordinates for the nave, so its centered on the
		 * camera.
		 */
		final float centerX = (CAMERA_WIDTH - this.mNaveTextureRegion
				.getWidth()) / 2;
		final float centerY = (CAMERA_HEIGHT - this.mNaveTextureRegion
				.getHeight()) / 2;

		this.nave = new Sprite(centerX, centerY + 42, this.mNaveTextureRegion,
				this.getVertexBufferObjectManager());

		FixtureDef FIXTURE_DEF = PhysicsFactory.createFixtureDef(0.8f, 0.2f,
				0.3f);
		navebody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, nave,
				BodyType.DynamicBody, FIXTURE_DEF);
		this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(nave,
				navebody, true, false));

		final PhysicsHandler physicsHandler = new PhysicsHandler(nave);
		nave.registerUpdateHandler(physicsHandler);
		this.mBoundChaseCamera.setChaseEntity(nave);
		scene.attachChild(nave);

		/* Controle de direcao e velocidade */
		final float x1 = 0;
		final float y1 = CAMERA_HEIGHT- this.mOnScreenControlBaseTextureRegion.getHeight();
		this.velocityOnScreenControl = new AnalogOnScreenControl(
				x1, y1, this.mBoundChaseCamera,
				this.mOnScreenControlBaseTextureRegion,
				this.mOnScreenControlKnobTextureRegion, 0.1f,
				this.getVertexBufferObjectManager(),
				new IAnalogOnScreenControlListener() {
					@Override
					public void onControlChange(
							final BaseOnScreenControl pBaseOnScreenControl,
							final float pValueX, final float pValueY) {
						final Body navebody = Planeta1.this.navebody;
						//if(!back.isPlaying())  back.start();//executa

						velocity = Vector2Pool.obtain(pValueX * velocidade,
								pValueY * velocidade);
						navebody.setLinearVelocity(velocity);
						Vector2Pool.recycle(velocity);

						physicsHandler.setVelocity(pValueX * velocidade,
								pValueY * velocidade);
						if (pValueX == x1 && pValueY == x1) {
							// nave.setRotation(x1);
						} else {
							nave.setRotation(MathUtils.radToDeg((float) Math
									.atan2(pValueX, -pValueY)));
						}
					}

					@Override
					public void onControlClick(
							final AnalogOnScreenControl pAnalogOnScreenControl) {
						/* Nothing. */
					}
				});
		this.velocityOnScreenControl.getControlBase().setBlendFunction(
				GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA);
		this.velocityOnScreenControl.getControlBase().setAlpha(0.5f);
		
		
		scene.setChildScene(this.velocityOnScreenControl);

		/* Botão de atirar */
		Sprite botaoAtirar = new Sprite(
				(CAMERA_WIDTH - this.mOnScreenControlBaseTextureRegion
						.getWidth()) + 80,
				((this.mPlaceOnScreenControlsAtDifferentVerticalLocations) ? 0
						: y1) + 80, botaoConsumableTextureRegion, this
						.getVertexBufferObjectManager()) {
			@Override
			public boolean onAreaTouched(final TouchEvent pSceneTouchEvent,
					final float pTouchAreaLocalX, final float pTouchAreaLocalY) {

				if (!Cooldown.getSharedInstance().checkValidity()) {
					return false;
				}else{
				
				float pX = nave.getX() + nave.getHeight() / 2;
				float pY = nave.getY() + nave.getWidth() / 2;
				float rotacao = nave.getRotation();

				Planeta1.this.Atirar(pX, pY, rotacao, 2, 25, 0);
				return true;
				}
			}
		};

		hud.attachChild(botaoAtirar);
		hud.registerTouchArea(botaoAtirar);
		botaoAtirar.setAlpha(0.5f);

		/* Texto do score */
		textRight = new Text(CAMERA_WIDTH
				- this.mOnScreenControlBaseTextureRegion.getWidth() + 10, 0,
				this.mFont, "Score: 000000000",
				this.getVertexBufferObjectManager());
		hud.attachChild(textRight);
		increaseScore(0);

		/* Botao da arma normal */
		Sprite armaNormal = new Sprite(
				(CAMERA_WIDTH - this.mOnScreenControlBaseTextureRegion
						.getWidth()) + 80,
				((this.mPlaceOnScreenControlsAtDifferentVerticalLocations) ? 0
						: y1) + 20, botaoEspecialTextureRegion, this
						.getVertexBufferObjectManager()) {
			@Override
			public boolean onAreaTouched(final TouchEvent pSceneTouchEvent,
					final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
				if (contCast == 150 && energia >= 81) {
					decreaseEnergy(81);
					barraDeCast();// ativa a Hipervelocidade
				}
				return true;
			}
		};
		hud.attachChild(armaNormal);
		hud.registerTouchArea(armaNormal);
		armaNormal.setAlpha(0.5f);

		/* Botao da arma especial */
		Sprite armaEspecial = new Sprite(
				(CAMERA_WIDTH - this.mOnScreenControlBaseTextureRegion
						.getWidth()) + 35,
				((this.mPlaceOnScreenControlsAtDifferentVerticalLocations) ? 0
						: y1) + 35, botaoEspecialTextureRegion, this
						.getVertexBufferObjectManager()) {
			@Override
			public boolean onAreaTouched(final TouchEvent pSceneTouchEvent,
					final float pTouchAreaLocalX, final float pTouchAreaLocalY) {

				if (!Cooldown.getSharedInstance().checkValidity()) {
					return false;
				}else{
					if(energia>=30){
				decreaseEnergy(30);
				float pX = nave.getX() + nave.getHeight() / 2;
				float pY = nave.getY() + nave.getWidth() / 2;
				float rotacao = nave.getRotation();

				Planeta1.this.Atirar(pX, pY, rotacao, 2, 75, 1);
				return true;
				}else{
					return false;
				}
				}
			}
		};
		hud.attachChild(armaEspecial);
		hud.registerTouchArea(armaEspecial);
		armaEspecial.setAlpha(0.5f);

		/* Botao do item consumivel */
		Sprite consumable = new Sprite(
				(CAMERA_WIDTH - this.mOnScreenControlBaseTextureRegion
						.getWidth()) + 20,
				((this.mPlaceOnScreenControlsAtDifferentVerticalLocations) ? 0
						: y1) + 80, botaoConsumableTextureRegion, this
						.getVertexBufferObjectManager()) {
			@Override
			public boolean onAreaTouched(final TouchEvent pSceneTouchEvent,
					final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
				decreaseLife(10);
				return true;
			}
		};
		hud.attachChild(consumable);
		hud.registerTouchArea(consumable);
		consumable.setAlpha(0.5f);

		mBoundChaseCamera.setHUD(hud);

		scene.registerUpdateHandler(new IUpdateHandler() {
			@Override
			public void reset() {
			}

			@Override
			public void onUpdate(final float pSecondsElapsed) {
				// metodo clear some os tiros
				cleaner(); 
				cleanerTiroEnemy();
				
				if(vida==0){
					gameOver();
				}
				//teste o inimigo 3 ficar atirando.
				if (contador==25){
					enemyAtirar(enemy3.getX()+enemy3.getHeight()/2,enemy3.getY()+enemy3.getWidth()/2, enemy3.getRotation(), 3);
					contador=0;
				}else{
					contador++;
				}
				
				//------------------ nave recebendo tiro--------------------
				if (enemyTiro.sprite.collidesWith(nave)){
					enemyTiro.sprite.setVisible(false);
					enemyTiro.sprite.setPosition(-50, -50);
					enemyTiro.sprite.detachSelf();
					bulletListEnemy.remove(enemyTiro);
					scene.detachChild(enemyTiro.sprite);
					
					decreaseLife(25);
					
				}
				//----------------------------------------------------------------
				
				//se o inimigo n�o tiver descartado, ele vai fazer o calculo do dano
				if(!enemy1.isDisposed()){
				if (enemy1.collidesWith(b.sprite)) {
					
					lifeEnemy1 = lifeEnemy1 - b.getPoderDano();
					b.sprite.setVisible(false);
					b.sprite.setPosition(-150,-150);
					b.sprite.clearEntityModifiers();
					b.sprite.clearUpdateHandlers();
					bulletList.remove(b);
					b.sprite.detachSelf();
					scene.detachChild(b.sprite);
					
					

					if (lifeEnemy1 <= 0) {
						lifeEnemy1 = 0;
						//enemy1.setVisible(false);
						
						enemy1.clearEntityModifiers();
						enemy1.clearUpdateHandlers();
						enemy1.setVisible(false);
						enemy1.detachSelf();
						scene.detachChild(enemy1);
						
						enemy1.dispose();
					
						increaseScore(100);
					}
			
					
					//------------ colocar son de Explos�o aki----------------
					
					
					//------------------------------------------------------------
				}
				if (enemy1.collidesWith(nave)) {
					decreaseLife(1);
				}
				}

				//se o inimigo n�o tiver descartado, ele vai fazer o calculo do dano
				if(!enemy2.isDisposed()){
				if (enemy2.collidesWith(b.sprite)) {
					lifeEnemy2 = lifeEnemy2 - b.getPoderDano();
					b.sprite.setVisible(false);
					b.sprite.setPosition(-150,-150);
					b.sprite.clearEntityModifiers();
					b.sprite.clearUpdateHandlers();
					bulletList.remove(b);
					b.sprite.detachSelf();
					scene.detachChild(b.sprite);
					
					
					if (lifeEnemy2 <= 0) {
						lifeEnemy2 = 0;
						
						
						
				
						enemy2.clearEntityModifiers();
						enemy2.clearUpdateHandlers();
						enemy2.setVisible(false);
						enemy2.detachSelf();
						scene.detachChild(enemy2);
						enemy2.dispose();
						
						quadri.setActive(false);
						Planeta1.this.mPhysicsWorld.destroyBody(quadri);
						increaseScore(100);
						
					}
			
				}

				if (enemy2.collidesWith(nave)) {
					decreaseLife(5);
				}
			}
				}
		});

		// Add os elementos do jogo que sao iniciados nesses metodos.
		this.iniciarAtores();
		this.carregarBordas();
		this.addBarraDeProgresso();
		this.scene.registerUpdateHandler(this.mPhysicsWorld);

		return scene;
	}

	/**
	 * Botao voltar
	 */
	public void onBackPressed() {
		
		//if(!back.isPlaying())back.stop(); //para a musica de fundo
		
		Intent telacad = new Intent(Planeta1.this, StageSelection.class);
		Planeta1.this.startActivity(telacad);
		Planeta1.this.finish();

		super.onBackPressed();
		return;
	}
	
	public void gameOver(){
	
			this.scene.setChildScene(this.mMenuScene, false, true, true);
			hud.setVisible(false);
		
	}
	
	@Override
	public boolean onKeyDown(final int pKeyCode, final KeyEvent pEvent) {
		if(pKeyCode == KeyEvent.KEYCODE_MENU && pEvent.getAction() == KeyEvent.ACTION_DOWN) {
			
			if(menuClickCont==0){
				this.scene.setChildScene(this.mMenuScene, false, true, true);
				menuClickCont=1;
				hud.setVisible(false);
			}else{
				this.mMenuScene.back();
				menuClickCont=0;
				scene.setChildScene(this.velocityOnScreenControl);
				hud.setVisible(true);
			}
			
		
			return true;
		} else {
			return super.onKeyDown(pKeyCode, pEvent);
		}
	}

	@Override
	public boolean onMenuItemClicked(final MenuScene pMenuScene, final IMenuItem pMenuItem, final float pMenuItemLocalX, final float pMenuItemLocalY) {
		switch(pMenuItem.getID()) {
			case MENU_RESET:
				/* Restart the animation. */
				this.scene.reset();
				
				//testes
				//-----------restaurar a vida------------
				vida = 160;
				increaseLife(160);
				/* Remove the menu and reset it. */
				this.scene.clearChildScene();
				
				this.mMenuScene.reset();
				menuClickCont=0;
				
				//---- teste pra iniciar a fase do inicio--------
				///Intent telacad = new Intent(Planeta1.this, Planeta1.class);
				///Planeta1.this.startActivity(telacad);
				///Planeta1.this.finish();
				
				//----- continuar de onde tava-----------
				scene.setChildScene(this.velocityOnScreenControl);
				hud.setVisible(true);
				
				return true;
			case MENU_QUIT:
				/* End Activity. */
				this.finish();
				return true;
			default:
				return false;
		}
	}

	protected void createMenuScene() {
		this.mMenuScene = new MenuScene(this.mBoundChaseCamera);
		
		final SpriteMenuItem resetMenuItem = new SpriteMenuItem(MENU_RESET, this.mMenuResetTextureRegion, this.getVertexBufferObjectManager());
		resetMenuItem.setBlendFunction(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA);
		this.mMenuScene.addMenuItem(resetMenuItem);

		final SpriteMenuItem quitMenuItem = new SpriteMenuItem(MENU_QUIT, this.mMenuQuitTextureRegion, this.getVertexBufferObjectManager());
		quitMenuItem.setBlendFunction(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA);
		this.mMenuScene.addMenuItem(quitMenuItem);

		this.mMenuScene.buildAnimations();

		this.mMenuScene.setBackgroundEnabled(false);

		this.mMenuScene.setOnMenuItemClickListener(this);
	}

	/**
	 * Adiciona bordas ao mapa
	 */
	private void carregarBordas() {

		final VertexBufferObjectManager vertexBufferObjectManager = this
				.getVertexBufferObjectManager();
		final Rectangle bottom = new Rectangle(0, tmxLayer.getHeight() - 2,
				tmxLayer.getWidth(), 2, vertexBufferObjectManager);
		final Rectangle top = new Rectangle(0, 0, tmxLayer.getWidth(), 2,
				vertexBufferObjectManager);
		final Rectangle left = new Rectangle(0, 0, 2, tmxLayer.getHeight(),
				vertexBufferObjectManager);
		final Rectangle right = new Rectangle(tmxLayer.getWidth() - 2, 0, 2,
				tmxLayer.getHeight(), vertexBufferObjectManager);

		bottom.setColor(Color.BLACK);
		top.setColor(Color.BLACK);
		left.setColor(Color.BLACK);
		right.setColor(Color.BLACK);
		/*
		 * Cria um PhysicsWorld. Este eh o responsavel por controlar toda a
		 * fisica do seu jogo. eh este objeto que vai tratar a logica da
		 * gravidade, velocidade, elasticidade, etc
		 */
		/*
		 * FixtureDef eh a classe responsavel pro definir as propriedades
		 * fisicas do objeto no mundo fisico. Possui 3 parametros: Densidade,
		 * elasticidade e friccao. sao valores float, onde o mais comum eh ir de
		 * 0 ate 1, porem pode ser adicionado qualquer float.
		 */

		final FixtureDef f = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f);

		/*
		 * Body eh a classe responsavel por representar o objeto grafico no
		 * Physcs World. Os seus parametros sao: o PhysicsWorld a que pertecem,
		 * qual eh o objeto grafico que ele pertence, qual o tipo de Body(pode
		 * ser dynamic(dinamico):responde as interacoes de colisao mudando a
		 * velocidade, a rotacao e a posicao; static: Nao reage as interacoes de
		 * colisao nem a gravidade. Normalmente sao obstaculos estaticos;
		 * KinematicBody: Nao vejo diferenca entre ele e o static.)
		 * 
		 * e o ultimo parametro eh o FixtureDef do corpo, ou seja a sua
		 * composicao fisica.
		 */
		PhysicsFactory.createBoxBody(this.mPhysicsWorld, top,
				BodyType.StaticBody, f);
		PhysicsFactory.createBoxBody(this.mPhysicsWorld, bottom,
				BodyType.StaticBody, f);
		PhysicsFactory.createBoxBody(this.mPhysicsWorld, right,
				BodyType.StaticBody, f);
		PhysicsFactory.createBoxBody(this.mPhysicsWorld, left,
				BodyType.StaticBody, f);

		/*
		 * Registra uma conexao entre o Body e a sua imagem, para garantir que o
		 * que esta sendo mostrado na tela corresponde ao que esta acontecendo
		 * no PhysicsWorld
		 */

		this.scene.attachChild(top);
		this.scene.attachChild(bottom);
		this.scene.attachChild(left);
		this.scene.attachChild(right);

	}

	// os 2 quadrados que coloquei no mapa
	private void iniciarAtores() {
		this.enemy1 = new Rectangle(30, 30, 50, 100,
				this.getVertexBufferObjectManager());
		this.enemy1.setColor(111, 20, 40);

		this.enemy2 = new Rectangle(500, 500, 50, 100,
				this.getVertexBufferObjectManager());
		this.enemy2.setColor(111, 20, 40);

		FixtureDef FIXTURE_DEF = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f);
		quadri = PhysicsFactory.createBoxBody(this.mPhysicsWorld, enemy2,
				BodyType.DynamicBody, FIXTURE_DEF);
		this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(
				enemy2, quadri, true, false));

		final Path path = new Path(5).to(30, 30).to(30, 200).to(200, 200)
				.to(200, 30).to(30, 30);
		quadri.setActive(true);
		enemy1.registerEntityModifier(new LoopEntityModifier(new PathModifier(
				30, path, null, new IPathModifierListener() {
					@Override
					public void onPathStarted(final PathModifier pPathModifier,
							final IEntity pEntity) {

					}

					@Override
					public void onPathWaypointStarted(
							final PathModifier pPathModifier,
							final IEntity pEntity, final int pWaypointIndex) {
						switch (pWaypointIndex) {

						}
					}

					@Override
					public void onPathWaypointFinished(
							final PathModifier pPathModifier,
							final IEntity pEntity, final int pWaypointIndex) {

					}

					@Override
					public void onPathFinished(
							final PathModifier pPathModifier,
							final IEntity pEntity) {

					}
				})));

		this.scene.attachChild(enemy1);
		this.scene.attachChild(enemy2);
		
		this.enemy3 = new Rectangle(350, 350, 50, 50,
				this.getVertexBufferObjectManager());
		this.enemy3.setColor(111, 200, 50);
		 enemy3.registerEntityModifier(new LoopEntityModifier(
			        new RotationModifier(10, 0, 360)));
		 
		 enemy3Corpo = PhysicsFactory.createBoxBody(this.mPhysicsWorld, enemy3,
					BodyType.DynamicBody, FIXTURE_DEF);
			this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(
					enemy3, enemy3Corpo, true, true));
		 scene.attachChild(enemy3);
		 
		
	}
	
	// ===========================================================
	// Methods
	// ===========================================================	
	
	
	
	/**
	 * Incrementar pontuacao
	 * @param value
	 */
	public void increaseScore(int value) {
		score = score + value;
		textRight.setText("Score: " + (score));
	}

	/**
	 * Decrementar life
	 * O life cheio (100%) equivale a 160
	 * @param value
	 */
	public void decreaseLife(int value) {
		if ((life.getWidth() - value) <= 0) {
			life.setWidth(0);
			vida= 0;
		} else {
			life.setWidth(life.getWidth() - value);
			vida=vida-value;
		}
	}

	/**
	 * Incrementar life
	 * O life cheio (100%) equivale a 160
	 * @param value
	 */
	public void increaseLife(int value) {
		if ((life.getWidth() + value) >= 160) {
			life.setWidth(160);
			vida= 160;
		} else {
			life.setWidth(life.getWidth() + value);
			vida = vida+ value;
		}
	}

	/**
	 * Decrementar energia
	 * A barra de energia cheia (100%) equivale a 160
	 * @param value
	 */
	public void decreaseEnergy(int value) {
		int energiaAnterior = energia;
		if ((energy.getWidth() - value) <= 0) {
			energy.setWidth(0);
			energia = 0;
		} else {
			energy.setWidth(energy.getWidth() - value);
			energia = energia - value;
		}
		if (energiaAnterior == 160) {
			Planeta1.this.regenerateEnergy(5);
		}
	}

	/**
	 * Decrementar energia
	 * A barra de energia cheia (100%) equivale a 160
	 * @param value
	 */
	public void increaseEnergy(int value) {
		if ((energy.getWidth() + value) >= 160) {
			energy.setWidth(160);
			energia = 160;
		} else {
			energy.setWidth(energy.getWidth() + value);
			energia = energia + value;
		}
	}

	/**
	 * 
	 * @param value
	 */
	public void decreaseCast(int value) {
		if ((cast.getWidth() - value) <= 0) {
			cast.setWidth(0);
			contCast = 0;
		} else {
			cast.setWidth(cast.getWidth() - value);
			contCast = contCast - value;

		}
	}

	/**
	 * Adicionar as barras de progresso do jogo
	 */
	public void addBarraDeProgresso() {

		/* Barra do life */
		Planeta1.this.life = new Rectangle(10, 10, 160, 10,
				this.getVertexBufferObjectManager());
		life.setColor(Color.RED);
		Planeta1.this.hud.attachChild(life);

		/* Retangulo da energia */
		Planeta1.this.energy = new Rectangle(10, 25, 160, 10,
				this.getVertexBufferObjectManager());
		energy.setColor(Color.YELLOW);
		Planeta1.this.hud.attachChild(energy);

		Rectangle lifeBackground = new Rectangle(10, 10, 160, 10,
				this.getVertexBufferObjectManager());
		lifeBackground.setColor(Color.RED);
		lifeBackground.setAlpha(0.2f);
		Planeta1.this.hud.attachChild(lifeBackground);

		Rectangle energyBackground = new Rectangle(10, 25, 160, 10,
				this.getVertexBufferObjectManager());
		energyBackground.setColor(Color.YELLOW);
		energyBackground.setAlpha(0.2f);
		Planeta1.this.hud.attachChild(energyBackground);

		/* Retangulo do cast da velocidade */
		Planeta1.this.cast = new Rectangle(170, 280, 150, 10,
				this.getVertexBufferObjectManager());
		cast.setColor(Color.BLUE);
		Planeta1.this.hud.attachChild(cast);
		cast.setVisible(false);

		Planeta1.this.castBackground = new Rectangle(170, 280, 150, 10,
				this.getVertexBufferObjectManager());
		castBackground.setColor(Color.BLUE);
		castBackground.setAlpha(0.2f);
		Planeta1.this.hud.attachChild(castBackground);
		castBackground.setVisible(false);
	}

	/**
	 * Fazer a nave atirar
	 * @param x0
	 * @param y0
	 * @param rotacao
	 * @param tempo
	 * @param poderDoDano � a quantidade de dano que ira causar
	 * @param tipoDeTiro: 0 = tiro normal, sprit do tiro normal, 1 = tiro especial, sprit de tiro especial
	 * @return 
	 */
	private void Atirar(float x0, float y0, float rotacao, float tempo, int poderDoDano, int tipoDoTiro) {
		
		 tiro.release(); //prepara activity
         tiro = MediaPlayer.create(context , R.raw.lasershoot); //cria
         tiro.start();//executa
		
		Planeta1.this.b = new Bullet(tipoDoTiro);
		
		b.setPoderDano(poderDoDano);
		// no clique na imagem do tiro
		float r = 350;

		float pX = x0-(b.sprite.getHeight()/2);
		float pY = y0-(b.sprite.getWidth()/2);

		b.sprite.setPosition(pX, pY);
		
		scene.attachChild(b.sprite);
		b.addCordenadasIniciais(x0, y0);
		float angleRad = rotacao;

		float xsin = (float) Math.sin(angleRad * (Math.PI / 180));
		float ycos = (float) Math.cos(angleRad * (Math.PI / 180));

		float Vx = r * xsin;
		float Vy = r * ycos;

		float ptx = 0;
		float pty = 0;

		if ((angleRad <= 90) && (angleRad >= 0)) {
			ptx = pX + Vx;
			pty = pY - Vy;

		}
		if ((angleRad > 90) && (angleRad <= 180)) {
			ptx = pX + Vx;
			pty = pY + ((-1) * Vy);
		}
		if ((angleRad >= -90) && (angleRad < 0)) {
			ptx = pX - ((-1) * Vx);
			pty = pY - Vy;
		}
		if ((angleRad < -90) && (angleRad >= -(180))) {
			ptx = pX - ((-1) * Vx);
			pty = pY + ((-1) * Vy);
		}
		
		
		
		b.sprite.setVisible(true);
	    b.sprite.detachSelf();
	    scene.attachChild(b.sprite);
	    Planeta1.this.bulletList.add(b);
	    Planeta1.this.bulletCount++;
	    
		MoveModifier mov = new MoveModifier(tempo, pX, ptx, pY, pty);
		b.sprite.registerEntityModifier(mov);
		
	}
	
	private void enemyAtirar(float x0, float y0, float rotacao, float tempo) {
		
		etiro.release(); //prepara activity
        etiro = MediaPlayer.create(context , R.raw.quickshot); //cria
        etiro.start();//executa
		
		Planeta1.this.enemyTiro = new BulletEnemy();
		// no clique na imagem do tiro
		float r = 350;

		float pX = x0;
		float pY = y0;

		enemyTiro.sprite.setPosition(x0-(enemyTiro.sprite.getHeight()/2), y0-(enemyTiro.sprite.getWidth()/2));
		
		
		enemyTiro.addCordenadasIniciais(x0, y0);
		float angleRad = rotacao;

		float xsin = (float) Math.sin(angleRad * (Math.PI / 180));
		float ycos = (float) Math.cos(angleRad * (Math.PI / 180));

		float Vx = r * xsin;
		float Vy = r * ycos;

		float ptx = 0;
		float pty = 0;

		if ((angleRad <= 90) && (angleRad >= 0)) {
			ptx = pX + Vx;
			pty = pY - Vy;

		}
		if ((angleRad > 90) && (angleRad <= 180)) {
			ptx = pX + Vx;
			pty = pY + ((-1) * Vy);
		}
		if ((angleRad >= -90) && (angleRad < 0)) {
			ptx = pX - ((-1) * Vx);
			pty = pY - Vy;
		}
		if ((angleRad < -90) && (angleRad >= -(180))) {
			ptx = pX - ((-1) * Vx);
			pty = pY + ((-1) * Vy);
		}
		
		
		
		enemyTiro.sprite.setVisible(true);
		enemyTiro.sprite.detachSelf();
	    scene.attachChild(enemyTiro.sprite);
	    Planeta1.this.bulletListEnemy.add(enemyTiro);
	   // Planeta1.this.bulletCount++;
	    
		MoveModifier mov = new MoveModifier(tempo, pX, ptx, pY, pty);
		enemyTiro.sprite.registerEntityModifier(mov);
		
	}

	/**
	 * Regenera a energia do player por segundo
	 * 
	 * @param i
	 *            Quantidade de energia que será incrementada a cada segundo
	 * @return True, se a operação foi bem sucedida
	 */
	public boolean regenerateEnergy(final int i) {

		Thread t = new Thread(new Runnable() {
			public void run() {

				while (energia < 160) {
					try { // Tenta pausar em 1000 milisegundos.
						Thread.sleep(1000);
						increaseEnergy(i);
					} catch (InterruptedException e) { // Erro na execucao.
						System.out.println("ERRO");
					}
				}

			}
		});

		t.start();
		return true;
	}

	public void barraDeCast() {
		final Thread tc = new Thread(new Runnable() {
			public void run() {

				Planeta1.this.cast.setVisible(true);
				Planeta1.this.castBackground.setVisible(true);
				Planeta1.this.velocidade = 15;

				while (contCast > 0) {
					try { // Tenta pausar em 120 milisegundos.
						Thread.sleep(250);
						decreaseCast(25);
					} catch (InterruptedException e) { // Erro na execucao.
						System.out.println("ERRO");
					}

				}
				Planeta1.this.cast.setVisible(false);
				Planeta1.this.castBackground.setVisible(false);
				Planeta1.this.cast.setWidth(150);
				Planeta1.this.velocidade = 5;
				Planeta1.this.contCast = 150;

			}

		});

		tc.start();

	} 
	
	public void cleaner() {
	    synchronized (this) {
	        Iterator<Bullet> it = bulletList.iterator();
	        while (it.hasNext()) {
	            Bullet b = (Bullet) it.next();
	            if (MathUtils.distance(b.getXInicial(), b.getYInicial(), b.sprite.getX(), b.sprite.getY())>=300) {
	            	b.sprite.clearEntityModifiers();
					b.sprite.clearUpdateHandlers();
					b.sprite.setVisible(false);
					b.sprite.detachSelf();
					scene.detachChild(b.sprite);
	                it.remove();
	                continue;
	            }
	        }
	    }
	}
	
	public void cleanerTiroEnemy() {
	    synchronized (this) {
	     
	        Iterator<BulletEnemy> inimigo = bulletListEnemy.iterator();
	        
	     
	            while (inimigo.hasNext()) {
		            BulletEnemy ini = (BulletEnemy) inimigo.next();
		            if (MathUtils.distance(ini.getXInicial(), ini.getYInicial(), ini.sprite.getX(), ini.sprite.getY())>=300) {
		            	ini.sprite.clearEntityModifiers();
		            	ini.sprite.clearUpdateHandlers();
		            	ini.sprite.setVisible(false);
						ini.sprite.detachSelf();
						scene.detachChild(ini.sprite);
		                inimigo.remove();
		                continue;
		            }
	        }
	    }
	}
	
	
	public  ITextureRegion getMBalaTextureRegion(){
		return  this.mBalaTextureRegion;
	}
	
	
	public  ITextureRegion getMBalasEspeciasTexture(){
		return  this.mBalaEspeciasTextureRegion;
	}

	

}
